<?php
namespace app\controller\admin;

use app\service\AuthService;
use support\Request;
use app\support\Response;
use Tinywan\Jwt\JwtToken;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("认证管理")
 * @Apidoc\Group("admin")
 */
class AuthController
{
    /**
     * @Apidoc\Title("登录")
     * @Apidoc\Method("POST")
     * @Apidoc\Url("/admin/Auth/login")
     * @Apidoc\ParamType("json")
     * @Apidoc\Param("username", type="string", require=true, desc="用户名")
     * @Apidoc\Param("password", type="string", require=true, desc="密码")
     */
    public function login(Request $request)
    {
        try {
            // 验证请求参数
            $username = $request->post('username');
            $password = $request->post('password');
            
            if (empty($username) || empty($password)) {
                return Response::error('用户名和密码不能为空', 400);
            }

            // 验证用户名密码
            $admin = AuthService::verify($username, $password);
            if (!$admin) {
                return Response::error('用户名或密码错误', 401);
            }

            // 检查用户状态
            if ($admin['status'] != 1) {
                return Response::error('账号已被禁用', 403);
            }

            // 生成 token
            $token = JwtToken::generateToken([
                'id' => $admin['id'],
                'username' => $admin['username']
            ]);

            return Response::success([
                'token' => $token,
                'expires_in' => $token['expires_in'],
                'user' => [
                    'id' => $admin['id'],
                    'username' => $admin['username'],
                    'real_name' => $admin['real_name'] ?? '',
                    'avatar' => $admin['avatar'] ?? ''
                ]
            ]);
        } catch (\Exception $e) {
            return Response::error($e->getMessage());
        }
    }

    /**
     * @Apidoc\Title("获取当前登录用户信息")
     * @Apidoc\Method("GET")
     * @Apidoc\Url("/admin/Auth/me")
     * @Apidoc\Returned("data", type="object", desc="用户信息", children={
     *   @Apidoc\Returned("id", type="int", desc="用户ID"),
     *   @Apidoc\Returned("username", type="string", desc="用户名"),
     *   @Apidoc\Returned("email", type="string", desc="邮箱"),
     *   @Apidoc\Returned("status", type="int", desc="状态")
     * })
     */
    public function me(Request $request)
    {
        try {
            $admin = AuthService::user();
            return Response::success($admin);
        } catch (\Exception $e) {
            return Response::error($e->getMessage());
        }
    }

    /**
     * @Apidoc\Title("退出登录")
     * @Apidoc\Method("POST")
     * @Apidoc\Url("/admin/Auth/logout")
     */
    public function logout(Request $request)
    {
        try {
            // 将当前 token 加入黑名单
            JwtToken::invalidToken();
            return Response::success(null, '退出成功');
        } catch (\Exception $e) {
            return Response::error($e->getMessage());
        }
    }
} 